package com.dman.multi.core;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.channels.UnresolvedAddressException;

import com.dman.multi.proxy.ProxyAdaptor;

public class ProxySettings implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String proxyHost;
	private int proxyPort;
	private Proxy.Type proxyType;
	private String userName;
	private String encryptedPassword;
	private boolean authSpecified;
	private transient ProxyAdaptor proxyAuth = null;
	
	public ProxySettings(String proxyHost, int proxyPort,
			Proxy.Type proxyType, boolean isAuthSpecified, String userName, String password) {
		this.proxyHost = proxyHost;
		this.proxyPort = proxyPort;
		this.proxyType = proxyType;
		this.authSpecified = isAuthSpecified;
		if(isAuthSpecified){
			this.userName = userName;
			this.encryptedPassword = password;
		}
		init();
	}
	
	private void init(){
		if(proxyPort < 0 && proxyPort > 65536)
			throw new NumberFormatException("The port number must be between 1 & 65535");
		InetSocketAddress isa = new InetSocketAddress(proxyHost, proxyPort);
		if(isa.isUnresolved())
			throw new UnresolvedAddressException();
		Proxy proxy = Proxy.NO_PROXY;
		if(proxyType != Proxy.Type.DIRECT)
			proxy = new Proxy(proxyType, isa);
		proxyAuth = new ProxyAdaptor(proxy, authSpecified?(userName + ":" + encryptedPassword):null);
	}
	
	private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException{
		ois.defaultReadObject();
		init();
	}

	public String getUserName(){
		return userName;
	}
	
	public String getEncryptedPassword() {
		return encryptedPassword;
	}

	public String getProxyHost() {
		return proxyHost;
	}

	public int getProxyPort() {
		return proxyPort;
	}

	public Proxy.Type getProxyType() {
		return proxyType;
	}
	
	public ProxyAdaptor getProxyAuth() {
		return proxyAuth;
	}
	
	public boolean isAuthSpecified() {
		return authSpecified;
	}
}